// axios二次封装
import axios from "axios";
import enConfig from "./env";
import { ElMessage } from "element-plus";
// 引入进度条
import NProgress from "nprogress";
// 创建axios实例
const service = axios.create({
    // 设置基地址
    baseURL: enConfig.port.baseURL,
    timeout: 5000,
});

// 创建请求拦截器
service.interceptors.request.use(
    (config) => {
        NProgress.start();
        if (config.url !== "/login") {
            config.headers["Authorization"] = sessionStorage.getItem("token");
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 创建响应拦截器
service.interceptors.response.use(
    (res) => {
        NProgress.done();
        console.log("res:::", res);
        const {
            meta: { msg, status: code },
            data: result,
        } = res.data;
        const successCodeArr = [200, 201, 204];
        if (successCodeArr.includes(code)) {
            ElMessage({
                message: msg,
                type: "success",
            });

            if (res.config.url === "/login") {
                sessionStorage.setItem("token", result.token);
            }
            return result;
        }

        ElMessage({
            message: msg,
            type: "error",
        });
        return Promise.reject(msg);
    },
    (error) => {
        return Promise.reject(error);
    }
);

export default service;